//
//  CAIUpgradeAlert.m
//  CHSUpgradeManager
//
//  Created by 海参 on 2021/9/16.
//

#import "CAIUpgradeAlert.h"
#import "CAIUpgradeContentTableCell.h"

#import <Masonry/Masonry.h>
#import "CAIUpgradeTool.h"

/** 入场出场动画时间 */
static const CGFloat kAnimationTimeInterval = 0.3f;


@interface CAIUpgradeAlert ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UIImageView *iconImageView;


@property (nonatomic, strong) UILabel *titleLab;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, strong) UIButton *nextButton;

@property (nonatomic, strong) UIButton *cancelButton;



@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *content;

@property (nonatomic, copy) NSArray *contentSepArray;


/// 确认事件
@property (nonatomic, copy) void(^nextBlock)(void);
/// 取消事件
@property (nonatomic, copy) void(^cancelBlock)(void);
/// 是否强制
@property (nonatomic, assign) BOOL isForce;
@end


@implementation CAIUpgradeAlert

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
///会崩溃
- (void)dealloc{
    //    [self.tableView removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize))];
}

+ (CAIUpgradeAlert *)showAlertWithImage:(nullable UIImage *)image
                                  title:(NSString *)title
                                content:(nullable NSString *)content
                                isForce:(BOOL)isForce
                              nextBlock:(nullable void(^)(void))nextBlock
{
    
    CAIUpgradeAlert *alertView = [[CAIUpgradeAlert alloc] initWithImage:image title:title content:content];
    alertView.nextBlock = nextBlock;
    alertView.isForce = isForce;
    [[CAIUpgradeTool mainWindow] addSubview:alertView];
    [alertView show];
    return alertView;
}

- (instancetype)initWithImage:(nullable UIImage *)image
                        title:(NSString *)title
                      content:(NSString * _Nullable)content
{
    CAIUpgradeAlert *alertView = [[CAIUpgradeAlert alloc] init];
    alertView.title = title;
    alertView.content = content;
    return alertView;
}


- (instancetype)initWithFrame:(CGRect)frame{
    
    if(self = [super initWithFrame:frame])
    {
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        // 配置UI
        [self configUI];
        [self configConstraints];
        [self setData];
    }
    return self;
}

- (void)configUI {
    
    self.backgroundColor =[UIColor caiUpdateColorWithHexString:@"000000" alpha:0.65];;
    
    [self addSubview:self.containerView];
    
    [self.containerView addSubview:self.bgView];
    
    [self.bgView addSubview:self.iconImageView];
    [self.bgView addSubview:self.titleLab];
    [self.bgView addSubview:self.tableView];
    
    UIColor *startColor =[UIColor caiUpdateColorWithHexString:@"#FE771E"];;
    UIColor *endColor =[UIColor caiUpdateColorWithHexString:@"#FF470F"];;
    
    UIImage *backgroundImage = [CAIUpgradeAlert gradientGeneralHorizontalDoubleColorImageWithSize:CGSizeMake(LCDScale_iPhone6(279), 40) startColor:startColor endColor:endColor];
    [self.nextButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    [self.bgView addSubview:self.nextButton];
    
    [self.containerView addSubview:self.cancelButton];
}


- (void)configConstraints
{
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(LCDScale_iPhone6(32));
        make.centerY.mas_equalTo(self.mas_centerY).offset(LCDScale_iPhone6(-20));
        make.centerX.mas_equalTo(self.mas_centerX);
    }];
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.containerView.mas_left);
        make.centerX.mas_equalTo(self.containerView.mas_centerX);
        make.top.mas_equalTo(self.containerView.mas_top).offset(0);
    }];
    
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(self.bgView.mas_centerX);
        make.top.mas_equalTo(self.containerView.mas_top).offset(LCDScale_iPhone6(37));
        make.height.mas_equalTo(LCDScale_iPhone6(134));
        
    }];
    
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.bgView.mas_left).offset(LCDScale_iPhone6(16));
        make.centerX.mas_equalTo(self.bgView.mas_centerX);
        make.top.mas_equalTo(self.bgView.mas_top).offset(LCDScale_iPhone6(200));
    }];
    
    //tableView方案
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.bgView.mas_left).offset(LCDScale_iPhone6(24));
        make.centerX.mas_equalTo(self.bgView.mas_centerX);
        make.top.mas_equalTo(self.titleLab.mas_bottom).offset(LCDScale_iPhone6(20-4.5));
        make.height.mas_equalTo(LCDScale_iPhone6(60));
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.bgView.mas_left).offset(LCDScale_iPhone6(16));
        make.centerX.mas_equalTo(self.bgView.mas_centerX);
        make.height.mas_equalTo(LCDScale_iPhone6(40));
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(LCDScale_iPhone6(29-4.5));
        make.bottom.mas_equalTo(self.bgView.mas_bottom).offset(-LCDScale_iPhone6(16));
    }];
    
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.containerView.mas_centerX);
        make.height.width.mas_equalTo(LCDScale_iPhone6(40));
        make.top.mas_equalTo(self.bgView.mas_bottom).offset(LCDScale_iPhone6(16));
        make.bottom.mas_equalTo(self.containerView.mas_bottom);
        
    }];
}



- (void)setData{
    
    self.cancelButton.hidden = self.isForce;
    
    [self.tableView addObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize)) options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
}

- (void)setTitle:(NSString *)title{
    if (_title != title) {
        _title = title;
        self.titleLab.text = title;
    }
}

- (void)setContent:(NSString *)content{
    if (_content != content) {
        _content = content;
        self.contentSepArray = [content componentsSeparatedByString:@"\n"];
    }
    [self.tableView reloadData];
}



- (void)setIsForce:(BOOL)isForce{
    if (_isForce != isForce) {
        _isForce = isForce;
        self.cancelButton.hidden = isForce;
    }
}


- (void)setAlertConfig:(CAIUpdateAlertConfiguration *)alertConfig{
    if (_alertConfig != alertConfig) {
        _alertConfig = alertConfig;
        if (alertConfig) {
            if (alertConfig.iconImage) {
                self.iconImageView.image = alertConfig.iconImage;
            }
            if (alertConfig.doButtonBackgroundColor) {
                [self.nextButton setBackgroundImage:nil forState:UIControlStateNormal];
                [self.nextButton setBackgroundColor:alertConfig.doButtonBackgroundColor];
            }
            if (alertConfig.doButtonBackgroundImage) {
                [self.nextButton setBackgroundImage:alertConfig.doButtonBackgroundImage forState:UIControlStateNormal];
            }
            
            [self.nextButton setTitle:alertConfig.doButtonTitle forState:UIControlStateNormal];
            if (alertConfig.doButtonCornerType == UpgradeDoButtonCornerTypePlain) {
                self.nextButton.layer.cornerRadius = alertConfig.doButtonCornerRadius;
            }else{
                self.nextButton.layer.cornerRadius = LCDScale_iPhone6(40)/2;
            }
        }
    }
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentSize"] && object == self.tableView) {
        if (self.contentSepArray.count == 0) {
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.titleLab.mas_bottom).offset(0);
                make.height.mas_equalTo(0);
            }];
            
        }else{
            CGFloat contentHeight = self.tableView.contentSize.height;
            CGFloat maxHeight = contentHeight > LCDScale_iPhone6(60) ?LCDScale_iPhone6(60):contentHeight;
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.titleLab.mas_bottom).offset(LCDScale_iPhone6(21));
                make.height.mas_equalTo(maxHeight);
            }];
        }
    }
}

#pragma mark - Action
// 取消
- (void)cancelClick:(UIButton *)sender {
    [self hide];
}

// 确定
- (void)nextClick:(UIButton *)sender {
    if (self.nextBlock) {
        self.nextBlock();
    }
    if (!self.isForce) {
        [self hide];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self updateRadiu];
}


#pragma mark - private
// 圆角
- (void)updateRadiu {
    self.bgView.layer.cornerRadius = 8;
    self.bgView.layer.masksToBounds = YES;
}


#pragma mark -

- (UIView *)containerView{
    
    if (!_containerView) {
        UIView *view  = [[UIView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        _containerView = view;
    }
    return _containerView;
}

- (UIView *)bgView{
    
    if (!_bgView) {
        UIView *view  = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        _bgView = view;
    }
    return _bgView;
}

- (UIImageView *)iconImageView{
    if (!_iconImageView) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [CAIUpgradeTool bundleImageNamed:@"upgrade_img_icon"];
        _iconImageView = imageView;
    }
    return _iconImageView;
}

- (UILabel *)titleLab
{
    if (!_titleLab) {
        UILabel *lab = [[UILabel alloc] init];
        lab.font = [UIFont systemFontOfSize:LCDScale_iPhone6(18) weight:UIFontWeightMedium];
        lab.textColor = [UIColor caiUpdateColorWithHexString:@"#333333"];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.numberOfLines = 0;
        lab.text = NSLocalizedString(@"", nil);
        _titleLab = lab;
    }
    return _titleLab;
}



-(UITableView *)tableView
{
    if (!_tableView) {
        UITableView *view = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        view.delegate = self;
        view.dataSource = self;
        view.separatorStyle = UITableViewCellSeparatorStyleNone;
        view.rowHeight = UITableViewAutomaticDimension;
        view.alwaysBounceVertical = NO;
        [view registerClass:[CAIUpgradeContentTableCell class] forCellReuseIdentifier:NSStringFromClass([CAIUpgradeContentTableCell class])];
        view.tableFooterView = nil;
        _tableView = view;
    }
    return _tableView;
}


- (UIButton *)nextButton
{
    if (!_nextButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"立即体验" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:LCDScale_iPhone6(16)];
        [btn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.layer.cornerRadius = LCDScale_iPhone6(6);
        btn.layer.masksToBounds = YES;
        _nextButton = btn;
    }
    return _nextButton;
}


- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(cancelClick:) forControlEvents:UIControlEventTouchUpInside];
        //        [btn setBackgroundColor:[UIColor redColor]];
        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"CHSUpgradeManager" ofType:@"bundle"]];
        UIImage *img = [UIImage imageNamed:@"upgrade_cancel_icon" inBundle:bundle compatibleWithTraitCollection:nil];
        [btn setImage:img forState:UIControlStateNormal];
        _cancelButton = btn;
    }
    return _cancelButton;
}


#pragma mark - DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contentSepArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CAIUpgradeContentTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CAIUpgradeContentTableCell class]) forIndexPath:indexPath];
    //    cell.contentView.backgroundColor = tableView.backgroundColor;
    [cell setData:[self.contentSepArray objectAtIndex:indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

+ (UIImage *)gradientGeneralHorizontalDoubleColorImageWithSize:(CGSize)size startColor:(UIColor *)startColor endColor:(UIColor *)endColor
{
    CGFloat startRed, startGreen, startBlue,startAlpha;
    [startColor getRed:&startRed green:&startGreen blue:&startBlue alpha:&startAlpha];
    
    CGFloat endRed, endGreen, endBlue,endAlpha;
    [endColor getRed:&endRed green:&endGreen blue:&endBlue alpha:&endAlpha];
    
    const CGFloat location[] ={0,1};
    const CGFloat components[] ={
        startRed,startGreen,startBlue,startAlpha,
        endRed,endGreen,endBlue,endAlpha
    };
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //创建色彩空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //指定渐变色；colorSpace：颜色空间；components：颜色数组；locations：颜色所在位置（0～1）；count：渐变个数
    CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, location, 2);
    CGColorSpaceRelease(colorSpace);
    CGPoint startPoint = (CGPoint){0,0};
    CGPoint endPoint = (CGPoint){size.width,0};
    
    CGContextDrawLinearGradient(context, colorGradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation);
    CGGradientRelease(colorGradient);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


#pragma mark - animation
// 弹出动画
- (void)show {
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    CGRect rect = self.containerView.frame;
    rect.origin.y = SCREEN_HEIGHT;
    self.containerView.frame = rect;
    [UIView animateWithDuration:kAnimationTimeInterval animations:^{
        self.backgroundColor =  [UIColor caiUpdateColorWithHexString:@"#000000" alpha:0.5];
        CGRect rect = self.containerView.frame;
        rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2.0;
        self.containerView.frame = rect;
    } completion:^(BOOL finished) {
    }];
}

// 收回动画
- (void)hide {
    [UIView animateWithDuration:kAnimationTimeInterval animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        CGRect rect = self.containerView.frame;
        rect.origin.y = SCREEN_HEIGHT;
        self.containerView.frame = rect;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


@end
